﻿//bibaoke.com

using Less.Text;

namespace Less.SqlParser
{
    internal class SelectColumnCommaReader : ReaderBase
    {
        internal override ReaderBase Read()
        {
            Word word = this.ReadWord();

            Select select = this.CastToSelect();

            if (word.Separator.IsEmpty())
            {
                if (select.IsNotNull())
                {
                    select.ColumnsEnd = this.LastWord.WordEnd;
                }

                return this.Pass<EndReader>();
            }

            if (word.Separator == ",")
            {
                if (word.Content.IsWhiteSpace())
                {
                    return this.Pass<SelectColumnReader>();
                }
                else
                {
                    select.AddColumn(word);

                    return this.Pass<SelectColumnReader>();
                }
            }
            else if (word.Separator == ";")
            {
                if (select.IsNotNull())
                {
                    select.ColumnsEnd = this.LastWord.WordEnd;

                    select.End = word.End;
                }

                return this.Pass<ActionReader>();
            }
            else if (word.Separator.IsWhiteSpace())
            {
                if (word.Content.CompareIgnoreCase("from"))
                {
                    if (select.IsNotNull())
                    {
                        select.ColumnsEnd = this.LastWord.WordEnd;

                        select.From = new From(word.Begin);

                        select.CurrentClause = select.From;
                    }

                    return this.Pass<FromReader>();
                }
                else if (word.Content.CompareIgnoreCase("where"))
                {
                    if (select.IsNotNull())
                    {
                        select.ColumnsEnd = this.LastWord.WordEnd;

                        select.Where = new Where(word.Begin);

                        select.CurrentClause = select.Where;
                    }

                    return this.Pass<WhereReader>();
                }
                else if (ReaderBase.ActionNames.Contains(word.Content))
                {
                    if (select.IsNotNull())
                    {
                        select.ColumnsEnd = this.LastWord.WordEnd;

                        select.End = word.End;
                    }

                    return this.Pass<ActionReader>();
                }
                else
                {
                    throw new ParseException(word);
                }
            }

            return this.Pass<EndReader>();
        }
    }
}
